<!--级联选择M-->

<template>
  <div class="w-h-full" :style="{
    textAlign: 'center',
    lineHeight: $parent.$parent.layoutItem.layoutItemConfigData.height - 2 + 'px'
  }">
    <!--组件遮罩层，用于在设计器中显示-->
    <div v-if="shade" class="shade"></div>

    <Input ref="Input" v-model="inputValue"
           :type="'text'"
           :size="component.compConfigData.inputConfig.size"
           :placeholder="component.compConfigData.inputConfig.placeholder"
           :clearable="component.compConfigData.inputConfig.clearable"
           :disabled="component.compConfigData.inputConfig.disabled"
           :readonly="component.compConfigData.inputConfig.readonly"
           :icon="'ios-arrow-down'"
           :style="Object.assign({
            width: component.compConfigData.inputConfig.inputStyle.width,
            transform: 'scale('+component.compConfigData.inputConfig.inputStyle.scaleValue+')'
           }, inputStyleObject)"
           @on-focus="inputOnFocusHandler"
           @on-click="inputOnFocusHandler"
    />

    <van-popup v-model="visible"
               :position="component.compConfigData.position"
               :round="component.compConfigData.round"
               :closeOnClickOverlay="component.compConfigData.closeOnClickOverlay"
               :get-container="component.compConfigData.getContainer"
               :style="{ height: component.compConfigData.position == 'left' || component.compConfigData.position == 'right' ? '100%': '' }"
               @open="onOpenHandler"
    >
      <van-cascader
          v-model="value"
          :title="component.compConfigData.title"
          :placeholder="component.compConfigData.placeholder"
          :active-color="component.compConfigData.activeColor"
          :closeable="component.compConfigData.closeable"
          :show-header="component.compConfigData.showHeader"
          :options="cascaderData"
          :field-names="{
            text: 'label',
            value: 'value',
            children: 'children',
          }"
          @finish="onFinishHandler"
          @close="onCloseHandler"
      />
    </van-popup>
  </div>
</template>

<script>

  import FuncCompMixin from '@/mixin/FuncCompMixin'
  import PnDesigner from '@/utils/PnDesigner'

  import Cascader from 'vant/lib/cascader';
  import Popup from 'vant/lib/popup';
  import 'vant/lib/cascader/style';
  import 'vant/lib/popup/style';

  const _this = {
    name: 'VanCascaderComp', // 此名称必须填写，且必须与组件文件名相同
    mixins: [FuncCompMixin],
    components: {
      [Cascader.name]: Cascader,
      [Popup.name]: Popup
    },
    attr: {
      version: '1.0',
      configDataTemp: Object.assign({

        inputConfig: {
          size: 'large',
          placeholder: '请选择',
          clearable: false,
          disabled: false,
          readonly: true,
          inputStyle: {
            scaleValue: 1,
            width: '150px',
            backgroundColor: '#263238',
            color: '#fff',
            borderColor: '#2196f3'
          }
        },

        title: '请选择所在地区',
        placeholder: '请选择',
        activeColor: '#2196f3',
        closeable: true,
        showHeader: true,

        position: 'bottom',
        round: true,
        closeOnClickOverlay: true,
        getContainer: '#app',

        sendDataType: 'all', // 交互流中发送数据类型，all：取所有值，last：取最后一个值
        datasourceType: 'children',

        onFinishCode: ''

      }, PnDesigner.buildFuncCompDatasourceField({ // 如果组件需要配置数据源，则需要调用此函数构建数据源字段对象
        ds_resultObjTemplate: [
          {
            field: 'label',
            remark: '标签，必须项'
          },
          {
            field: 'value',
            remark: '值，必须项'
          },
          {
            field: 'children',
            remark: '子节点'
          },
          {
            field: 'id',
            remark: '唯一标识，当数据源结果集类型为pid类型时，必须定义id'
          },
          {
            field: 'pid',
            remark: '当数据源结果集类型为pid类型时，使用pid来关联父节点'
          },
        ],
        ds_resultObj: [
          {
            label: '广西壮族自治区',
            value: 'guangxi',
            children: [
              {
                label: '南宁市',
                value: 'nanning',
              },
              {
                label: '桂林市',
                value: 'guilin',
              },
              {
                label: '柳州市',
                value: 'liuzhou',
              },
              {
                label: '北海市',
                value: 'beihai',
              }
            ]
          }
        ],
        ds_useFilter: true, // 是否使用过滤器，默认不使用
        ds_useTimer: false, // 是否开启定时器配置，默认不开启
      }), PnDesigner.buildFuncCompGlobalField(), PnDesigner.buildFuncCompInteractionConfiguration([
        PnDesigner.buildFuncCompInteractionStreamItem('itemFinish', [
          PnDesigner.buildFuncCompInteractionFieldsMapItem('text','', '标签'),
          PnDesigner.buildFuncCompInteractionFieldsMapItem('value','', '值'),
        ])
      ]))
    },
    data() {
      return {
        visible: false,
        inputValue: '',
        value: ''
      }
    },
    destroyed() {
      this.$EventBus.$off('pn_show_van_cascader_m_'+this.component.id)
    },
    mounted() {
      this.init();

      if (!this.$store.state.release.pageMetadata) {
        this.$EventBus.$off('pn_show_van_cascader_m_'+this.component.id)
        this.$EventBus.$on('pn_show_van_cascader_m_'+this.component.id, () => {
          this.visible = !this.visible
        })
      }
    },
    methods: {
      init () { // 组价初始化函数，函数名必须使用init，不可更改
        this.initDatasource(() => {
          this.runCustomGlobalJsCode()
        }, (result) => {
          this.runCustomGlobalJsCode()
        });
      },

      inputOnFocusHandler () {
        this.visible = true
      },

      arrToTree (data) {
        let result = []
        if (!Array.isArray(data)) {
          return result
        }
        data.forEach(item => {
          delete item.children;
        });
        let map = {};
        data.forEach(item => {
          map[item.id] = item;
        });
        data.forEach(item => {
          let parent = map[item.pid];
          if (parent) {
            (parent.children || (parent.children = [])).push(item);
          } else {
            result.push(item);
          }
        });
        return result;
      },

      onOpenHandler () {
        this.visible = true
      },

      onFinishHandler ({ selectedOptions }) {
        let labels = selectedOptions.map(function (params) {
          return params.label
        })
        let values = selectedOptions.map(function (params) {
          return params.value
        })
        let sendObj = {}
        switch (this.component.compConfigData.sendDataType) {
          case "all":
            sendObj = {text: labels.toString(), value: values.toString()}
            break
          case "last":
            sendObj = {label: labels.pop(), value: values.pop()}
            break
        }
        this.inputValue = labels.pop()
        this.$PnDesigner.launchInteractionStream(this.component.compConfigData, 'itemFinish', sendObj)
        try {
          let value = this.value
          let selectedData = selectedOptions
          eval(this.component.compConfigData.onFinishCode)
        }catch (e) {
          console.error(e)
        }
        this.visible = false
      },

      onCloseHandler () {
        this.visible = false
      }
    },
    computed: {
      cascaderData () {
        let ds_resultObj = this.$PnUtil.deepClone(this.component.compConfigData.ds_resultObj)
        ds_resultObj = this.runCustomFilter(ds_resultObj)
        if (this.component.compConfigData.datasourceType == 'pid') {
          if (Array.isArray(ds_resultObj) && ds_resultObj[0].pid != undefined) {
            ds_resultObj = this.arrToTree(ds_resultObj)
          }
        }
        return ds_resultObj
      },

      inputStyleObject () {
        return {
          '--background-color': this.component.compConfigData.inputConfig.inputStyle.backgroundColor,
          '--color': this.component.compConfigData.inputConfig.inputStyle.color,
          '--border-color': this.component.compConfigData.inputConfig.inputStyle.borderColor,
        }
      }
    }
  };

  export default _this
</script>

<style scoped>
div {
  color: #323233 !important;
}

>>> .ivu-input {
  background-color: var(--background-color);
  border: 1px solid var(--border-color);
  color: var(--color);
}
>>> .ivu-input::-webkit-input-placeholder{
  color: var(--color);
}
>>> .ivu-input::-moz-placeholder{
  color: var(--color);
}
>>> .ivu-input-icon {
  color: var(--color);
  font-size: 14px !important;
}
</style>
